package scparser.factory.sceneFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import model.Scene;
import model.lights.Light;
import scparser.ParserHelper;
import scparser.factory.lightFactory.LightAbstractFactory;
import scparser.factory.primitiveFactory.FactoryException;

public class SceneLightFactory extends SceneFactory {

	public SceneLightFactory(Scene scene) {
		super.scene = scene;
	}

	@Override
	public Object create(BufferedReader br) throws FactoryException {
		List<String> block = new ArrayList<String>();
		String line = null;
		String type = null;
		LightAbstractFactory pf = null;
		int brackets = 1;
		
		try {			
			while ((line = br.readLine()) != null) {
				line = line.trim();

				if (line.startsWith("type")) {
					type = ParserHelper.takeString(line, "type");
				} else if (line.contains("{")) {
					if (!line.contains("}")) {						
						brackets++;
					}
				} else if (line.contains("}")) {
					if (brackets == 0) {
						throw new FactoryException("syntax error, check your brackets");
					}

					if (brackets == 1) {
						break;
					}
					brackets--;
				}
				block.add(line);
			}
		} catch (IOException e) {
			throw new FactoryException(e.getMessage());
		}

		if (type == null) {
			throw new FactoryException("type missing");
		}
		
		if (type.equals("point")) {
			pf = new PointFactory(scene);
		}
		
		if (type.equals("meshlight")) {
			// future extension
		}
		
		if (type.equals("spherical")) {
			// future extension
		}
		
		Light ret = pf.create(block);
		if (super.scene.getLights().contains(ret)) {
			throw new FactoryException("shader already exists");
		}
		
		return ret;

	}
}

